package conf

import (
	"os"
	"runtime"
	"strings"

	"github.com/spf13/viper"
	"gopkg.in/yaml.v3"
)

type AppConfig struct {
	Mysql struct {
		Host     string `yaml:"host"`
		Port     string `yaml:"port"`
		User     string `yaml:"user"`
		Pass     string `yaml:"pass"`
		Name     string `yaml:"name"`
		Prefix   string `yaml:"prefix"`
		TimeZone string `yaml:"timezone"`
	}
	Secret string `yaml:"secret"`
	Redis  struct {
		Host   string `yaml:"host"`
		Port   int    `yaml:"port"`
		Pass   string `yaml:"password"`
		DB     int    `yaml:"db"`
		Prefix string `yaml:"prefix"`
	}
	Oss struct {
		Endpoint    string `yaml:"endpoint"`
		AccessKeyID string `yaml:"access_key_id"`
		AccessKey   string `yaml:"access_key"`
		Bucket      string `yaml:"bucket"`
		WebSite     string `yaml:"website"`
	}
}

var (
	v *viper.Viper
	//once sync.Once
	App *AppConfig
)

// init 初始化配置文件
func init() {
	data, err := os.ReadFile("./conf/config.yaml")
	if err != nil {
		panic(err.Error())
	}
	App = new(AppConfig)
	yaml.Unmarshal(data, App)
	v = viper.New()
	v.SetConfigName("config")
	dir, err := os.Getwd()
	if err != nil {
		panic(err.Error())
	}
	if runtime.GOOS == "windonws" {
		dir = strings.Replace(dir, "\\", "/", -1)
	}
	v.AddConfigPath(dir + "/conf")
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err.Error())
	}
}

// GetString 获取配置文件string类型的
func GetString(key string) string {
	//log.Println("GetString", key)
	return v.GetString(key)
}

// Get 获取interface{}类型的数据
func Get(key string) interface{} {
	return v.Get(key)
}

// GetInt 获取int类型的数据
func GetInt(key string) int {
	return v.GetInt(key)
}
